<?php
namespace control;


/*
*商城公告
*/

class announcementStoreClass extends adIndexClass
{
	private const page  = 'announcementStore';
	private const table = 'store_announcement';
	private const title = '商城公告';
	//
// aftermarketRegister
	public array $stateOption = ['草稿', '已发布'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '动态编号',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "分类",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 350,
                    ],
                    'passStid'         => [
                        'name'  => '发布人',
                        'width' => 200,
                    ],
                    'passTime'          => [
                        'name'  => '发布时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "动态编号" => text(array("name" => "orderNo")),
                    "标题"   => text(array("name" => "title")),
                    '发布时间' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    '分类'  => select(["name" => "type", 'option' => explode('，', para('dynamicType'))]),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('新建" . self::title . "','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//单据编号
			"title"   => $this->post('title'),//标题
		);
		//全等查询数组
		$equal = array(
			"type"  => $this->post('type'),//类别
			"state" => $this->post('state'),//状态
		);
		$and   = "";
		// if ($this->post('createTime')) {
		// 	$timeArr = explode(' ~ ', $this->post('createTime'));
		// 	$and     .= " and date(passTime) >='{$timeArr[0]}' and date(passTime) <='{$timeArr[1]}'";
		// }
		// if (!$this->power(self::page, 'seeAll')) {
		// 	$and .= " and member like '%{$this->control['stid']}%'";
		// }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [];
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
			$preview = "<span onclick=\"window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=previewPage&id={$array['id']}')\"><img src='" . root . "img/control/preview.svg' class='listIco'></span>";
            $liButton[] = $this->dominate($dominate). $preview;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "passStid":
                        $row[] = self::findStaff($array['passStid']);
                        break;
                    case "passTime":
                        $row[] = self::null($array['passTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$info   = query(self::table, " id = '" . $this->get('id') . "' ");
		$button = [];
		if ($this->power(self::page, "edit")) {
			//按钮
			$button[] = [
				"name"  => "保存",
				"type"  => "点击事件",
				"title" => "保存",
				"fun"   => "subContent('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
			];
		}

		//表单
        $data['button'] = $this->tableShowButton($button);
		$body = $this->edit4([
		    [
                [
                    must . "分类：" => select(["name" => "type", 'title' => '分类', 'class' => 'text', 'option' => explode('，', para('dynamicType')), "value" => $info['type']]),
                    must . "标题：" => text(["name" => "title", 'class' => 'text', "value" => $info['title']]),
                ],
                [
                    "摘要：" => textarea(["name" => "summary", "value" => $info['summary']]),
                ],
                [
                    "文章详情：" => "<div id='content'></div>",
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'], '公司动态', self::page, self::page . 'EditForm'),
                ],
            ]
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ? $info['id'] : $this->get('id')]),
		]);

		$data['html'] .= "
<script src='{$this->root}static/javascript/wangEditor.min.js'></script>
<script>
                                    var E = window.wangEditor;
                                    var content = new E(document.getElementById('content'));
                                     content.config.zIndex = 1;
                                     content.config.height  = 600;
                                    // 配置 server 接口地址
                                    content.config.uploadImgServer = root+'control/adIndex.html?cla={$this->get('cla')}&fun=savePic';
                                    content.config.pasteFilterStyle = true;
                                    content.config.uploadFileName = 'file[]';
                                    content.config.uploadImgMaxLength = 5
                                    content.create();
                                    content.txt.html(`" . html_entity_decode($info['content'], ENT_QUOTES) . "`);

</script>
";
		$data['html'] .= <<<efo
<script>
function subContent(form, url) {
//防止高频点击
    let date = new Date();
    let time = date.getTime();//毫秒时间戳
    let finger = 2;
    if (typeof minTime == "undefined") {
        minTime = time + 2000;//下次点击的最小时间
        console.log("定义minTime");
    } else {
        if (minTime && time < minTime) {
            finger = 1;
            warn("操作过于频繁");
            console.log("time:" + time + "，mintime:" + minTime + "，差额：" + (time - minTime));
        } else {
            finger = 2;
            console.log("time:" + time + "，mintime:" + minTime + "，多出：" + (time - minTime));
            minTime = time + 2000;//下次点击的最小时间
        }
    }
    if (finger === 2) {
        //串联表单
        var formData = new FormData($("[name='" + form + "']")[0]);
        formData.append('content', content.txt.html());
        //异步提交数据
        $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            // beforeSend: function () {
            //     console.log("正在进行，请稍候");
            // },
            success: function (res) {
                var data = JSON.parse(res);
                if (data.warn === 2) {
                    if (data.href) {//如果异步返回的json参数中定义了重定向url，则跳转到本url
                        window.location.href = data.href;
                    } else {
                        window.location.reload();
                    }
                } else {
                    warn(data.warn);
                }
            },
            error: function (responseStr) {
                console.log(responseStr);
            }
        });
    }
}
</script>
efo;

		//返回
		return $this->tab($data);
	}

	/**
	 * 保存富文本图片
	 *
	 * @return bool|string
	 */
	public function savePic()
	{
		$fileArr = $this->reArrayFiles($_FILES['file']);
		if (empty($fileArr) || !is_array($fileArr)) {
			$json['errno'] = $_FILES;
		} else {
			foreach ($fileArr as $file) {
				$result = $this->saveFile($file, self::page, explode(',', para('fileFormat')));
				if ($result['code']) {
					$json['data'][] = root . $result['src'];
				}
			}
			$json['errno'] = 0;
		}
		return json_encode($json, 320);
	}

	/**
	 * 多文件上传时重新组成文件上传格式数组
	 *
	 * @param $file_post
	 * @return array
	 */
	public function reArrayFiles($file_post): array
	{
		$file_ary = [];
		if (is_array($file_post)) {
			$file_count = count($file_post['name']);
			$file_keys  = array_keys($file_post);
			for ($i = 0; $i < $file_count; $i++) {
				foreach ($file_keys as $key) {
					$file_ary[$i][$key] = $file_post[$key][$i];
				}
			}
		}
		return $file_ary;
	}

	public function editEdit()
	{
		$id = $this->post('id') ?: self::getId();
		//附件
		$fileIdArr  = $this->post('fileId');
		$field      = [
			'type'       => $this->post('type'),
			'title'      => $this->post('title'),
			'summary'    => $this->post('summary'),
			"content"    => htmlentities($_POST['content'], ENT_QUOTES),//
			'updateTime' => $this->time,
		];
		$annotation = [
			'type'  => '分类',
			'title' => '标题',
		];
		$rules      = [
			'type'  => 'required',
			'title' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'NT' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $userNo,
					'stid'    => $this->control['stid'],
					'state'   => '草稿',
					'time'    => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加主表ID到附件表
				if (is_array($fileIdArr)) {
					update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
				}
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$_SESSION[self::page]['id'] = $info['id'];
			//菜单
			$data   = array(
				"id"    => $info['id'],
				"title" => self::title . '详情',
			);
			$button = [];
			if ($this->power(self::page, "edit")) {
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name" => "删除",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id']],
					];
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],

					];
				}
				$button[] = [
					"name"  => "预览",
					"type"  => "点击事件",
					"title" => "预览",
					'fun'   => "window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=previewPage&id={$info['id']}')",
				];
				switch ($info['state']) {
					case '已发布':
						$firState = '草稿';
						$titleOne = '撤销';
						break;
					default:
						$firState = '已发布';
						$titleOne = '发布';
						break;
				}
				//按钮
				$button[] = [
					"name"  => $titleOne,
					"type"  => "点击事件",
					"cla"   => $this->get('cla'),
					"fun"   => "layer('{$this->get('cla')}','stateSwitch',{type:'{$firState}',id:'{$info['id']}'})",
					'style' => 'li-btn-blue-bg',
				];
			}
			/*******附件****************/
			$fileCollection = fileUploadClass::showFile($info['id'], '公司动态');
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				'基本信息' => array(
					array(
						"动态编号" => $info['orderNo'],
						"创建人"   => self::findStaff($info['stid']),
						"创建时间" => $info['time'],
                        "分类" => $info['type'],
					),
					array(
						"标题" => $info['title'],
						"摘要" => $info['summary'],
                        "发布人"   => self::findStaff($info['passStid']),
                        "发布时间" => self::null($info['passTime']),
					),
					array(
						"状态"     => $info['state'],
					),
				),
				'文章详情' => array(
					array(
						pre(html_entity_decode($info['content'], ENT_QUOTES)),
					),
				),
				"附件"     => array(
					array(
						$fileCollection,
					),
				),
			));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	public function previewPage(): string
	{
		$obj        = new paperManagementClass();
		if ($this->get('source') == 'homepage') {
			//更新消息为已读
			update(array('table' => 'message', 'field' => ['see' => '是', 'seeTime' => $this->time], 'where' => " stid = '{$this->control['stid']}' and see = '否' and typeId = '{$this->get('id')}'"));
		}

		$info = query(self::table, " id = '{$this->get('id')}'");
		if ($info['state'] == '已发布') {
			$style = "display:block;";
		} else {
			$style = "display:none;";
		}
		$releaseName = self::findStaff($info['passStid']);

		$content       = html_entity_decode($info['content'], ENT_QUOTES);
		$result        = find(array('table' => " file where targetId !='' and targetId = '$info[id]' and target = '公司动态' order by time asc"));
		$topicItemText = '<ul>';
		foreach ($result['array'] as $array) {
			$preView       = fileUploadClass::view($array['src'], true, $array['name']);
			$topicItemText .= <<<efo

<li>{$array['name']} {$preView}</li>
efo;
		}
		$topicItemText .= '</ul>';
		if (is_array($result['array']) && count($result['array']) > 0) {
			$topicItemText = '<div style="font-weight: bold;margin-top: 10px">附件</div>' . $topicItemText;
		}
		$html = <<<efo
<div class="paper" style="width: 210mm;height: 97%;overflow: auto;background-color: #fff; margin: 0 auto;padding: 10px 30px">
<div class="paper-title-block" style="background-color: #fff;height: 55px;width: 210mm;line-height: 55px;">
<span class="paper-title-text" style="font-size: 18px;font-weight: bold">{$info['title']}</span>
</div>
<div style="{$style}height: 30px;line-height: 30px"><span style="font-weight: bold">发布人：</span>{$releaseName}&emsp;{$info['passTime']}</div>
<div style="margin-top: 10px">{$content}</div>
{$topicItemText}
</div>
efo;

		return $obj->header() . $this->style() . $html . $obj->footer();
	}

	/**
	 * 样式
	 *
	 * @return string
	 */
	public function style(): string
	{
		return <<<eof
        <style>
        body{
         background-color: #AAAAAA;
        }
       .topic-item ul li {
        margin-top: 10px;
       }
       .topic-block{
         margin: 25px 0 0 40px;
       }
        </style>
eof;
	}

	/**
	 * 发布/撤销
	 */
	public function stateSwitch()
	{
		$type = $this->post('type');
		if ($type == '草稿') {
			$title = "是否确认撤回此动态？";
		} else {
			$title = "是否确认发布此动态？";
		}
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					"提示：" => $title,
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $type)),
		));
		//返回
		return $this->layer(array("title" => "状态", "height" => 165, "html" => $html));
	}

	/**
	 * 发布/撤销
	 */
	public function stateSwitchEdit()
	{
		$id   = $this->post('id');
		$type = $this->post('type');
		$info = query(self::table, " id = '$id'");
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有" . self::title . "的编辑权限";
		} elseif (empty($info['id'])) {
			$json['warn'] = "未找到此动态";
		} elseif (!in_array($type, $this->stateOption)) {
			$json['warn'] = "类型错误";
		} else {
			$field = [
				'state' => $type,
			];
			if ($type == '已发布') {
				$field = array_merge($field, [
					'passTime' => $this->time,
					'passStid' => $this->control['stid'],
				]);
			} else {
				$field = array_merge($field, [
					'passTime' => '',
					'passStid' => '',
				]);
			}
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				if ($type == '草稿') {
					//撤销
					delete(array('table' => 'message', 'where' => " typeId = '$info[id]'"));
				} else {
					//发布
					$result = find(array('table' => 'staff', 'where' => " state not in ('离职')"));
					if (is_array($result['array'])) {
						foreach ($result['array'] as $array) {
							insert(array(
								'table' => 'message',
								'field' => [
									'stid'   => $array['stid'],
									'type'   => '公司动态',
									'typeId' => $info['id'],
									'text'   => $info['title'],
									'see'    => '否',
									'time'   => $this->time,
								],
							));
						}
					}
				}
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$type}】， id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = $word = '';
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				//最后删除基本参数
				delete(array("table" => self::table, "where" => " id = '$id' "));
				//返回
				$warn = "删除成功";
				$x++;
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


}
